﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Text;
using BookManager.Models;
using Newtonsoft.Json;

namespace BookClient
{
    public class Program
    {
        public static string Post(string url, string postData)
        {
            HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "POST";
            request.Timeout = 10000;

            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            request.ContentLength = bytes.Length;
            Stream Writer = request.GetRequestStream();
            Writer.Write(bytes, 0, bytes.Length);
            Writer.Close();

            HttpWebResponse response = (HttpWebResponse) request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), Encoding.UTF8);
            string result = reader.ReadToEnd();
            response.Close();
            return result;
        }


        public static void Main(string[] args)
        {
            // CreateWebHostBuilder(args).Build().Run();
            Console.WriteLine("Hello World!");
            string url = "http://localhost:42603/api/values";

            AddRequest req = new AddRequest();
            req.ISBN = "1";
            req.name = ".NET Core 从入门到入土";
            req.authors = null;
            req.price = 1.000M;

            string req_str=JsonConvert.SerializeObject(req);
            Console.WriteLine($"[REQ]{req_str}");

            string result = Post(url, req_str);
            Console.WriteLine($"[RESP]{result}");

            AddResponse resp = JsonConvert.DeserializeObject<AddResponse>(result);
            Console.WriteLine($"[resp.result]{resp.result}");
            if(resp.result=="s")
            {

            }
            else if(resp.result=="F")
            {
                
            }
            else
            {
                
            }
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}
